package cn.gok.thread;

/**
 * @ClassName 线程死锁
 * @Description TODO
 * @Author HP
 * @Date 10:18 2022/7/13
 * @Version 1.0
 **/
class A extends Thread{
    private String book1;
    private String book2;

    public A(String book1, String book2) {
        this.book1 = book1;
        this.book2 = book2;
    }

    @Override
    public void run() {
        synchronized (book2){
            System.out.println("A读了"+book2);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }synchronized (book1){
            System.out.println("A读了"+book1);
        }
    }
}
class B extends Thread{
    private String book1;
    private String book2;

    public B(String book1, String book2) {
        this.book1 = book1;
        this.book2 = book2;
    }

    @Override
    public void run() {
        synchronized (book2){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B读了"+book2);
        }synchronized (book1){
            System.out.println("B读了"+book1);
        }
    }
}
public class 线程死锁 {
    public static void main(String[] args) throws InterruptedException {
        A a = new A("西游记","红楼梦");
        B b = new B("西游记","红楼梦");
        a.start();
        a.join();
        b.start();
    }
}
